import { useEffect, useRef, useCallback } from 'react';
import { useAppDispatch } from '../store/hooks';
import { clearAuth } from '../store/slices/authSlice';
import { message } from 'antd';

// 会话超时时间（30分钟）
const SESSION_TIMEOUT = 30 * 60 * 1000; // 30分钟转换为毫秒

// 会话状态存储键名
const SESSION_STATE_KEY = 'session_state';

// 需要监听的用户活动事件
const ACTIVITY_EVENTS = [
  'mousedown',
  'mousemove',
  'keypress',
  'scroll',
  'touchstart',
  'click'
];

export const useSessionManager = (isAuthenticated: boolean = true) => {
  const dispatch = useAppDispatch();
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const lastActivityRef = useRef<number>(Date.now());
  const isActiveRef = useRef<boolean>(true);

  // 执行登出操作
  const performLogout = useCallback(() => {
    // 清除Redux状态
    dispatch(clearAuth());
    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    // 清除会话状态
    sessionStorage.removeItem(SESSION_STATE_KEY);
    // 显示超时提示
    message.warning('会话已超时，请重新登录');
    // 清除所有定时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, [dispatch]);

  // 重置会话超时计时器
  const resetSessionTimeout = useCallback(() => {
    // 清除现有的超时计时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    // 设置新的超时计时器
    timeoutRef.current = setTimeout(() => {
      performLogout();
    }, SESSION_TIMEOUT);

    // 更新最后活动时间
    lastActivityRef.current = Date.now();
  }, [performLogout]);

  // 处理用户活动
  const handleUserActivity = useCallback(() => {
    if (isActiveRef.current) {
      resetSessionTimeout();
    }
  }, [resetSessionTimeout]);

  // 处理页面可见性变化
  const handleVisibilityChange = useCallback(() => {
    if (document.hidden) {
      // 页面隐藏时暂停计时器
      isActiveRef.current = false;
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    } else {
      // 页面显示时恢复计时器
      isActiveRef.current = true;
      const timeSinceLastActivity = Date.now() - lastActivityRef.current;
      
      if (timeSinceLastActivity >= SESSION_TIMEOUT) {
        // 如果离开时间超过超时时间，直接登出
        performLogout();
      } else {
        // 否则重新设置计时器
        const remainingTime = SESSION_TIMEOUT - timeSinceLastActivity;
        timeoutRef.current = setTimeout(() => {
          performLogout();
        }, remainingTime);
      }
    }
  }, [performLogout]);

  // 处理页面卸载（关闭页面或刷新）
  const handleBeforeUnload = useCallback((event: BeforeUnloadEvent) => {
    // 保存当前会话状态到sessionStorage，用于页面刷新时恢复
    const currentTime = Date.now();
    const timeSinceLastActivity = currentTime - lastActivityRef.current;
    const remainingTime = Math.max(0, SESSION_TIMEOUT - timeSinceLastActivity);
    
    if (remainingTime > 0) {
      // 如果会话还有剩余时间，保存状态供刷新后恢复
      sessionStorage.setItem(SESSION_STATE_KEY, JSON.stringify({
        lastActivity: lastActivityRef.current,
        savedAt: currentTime
      }));
    } else {
      // 会话已过期，清除状态
      sessionStorage.removeItem(SESSION_STATE_KEY);
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      dispatch(clearAuth());
    }
  }, [dispatch]);

  // 初始化会话管理
  useEffect(() => {
    // 只有在用户已认证时才启用会话管理
    if (!isAuthenticated) {
      return;
    }

    // 检查是否有保存的会话状态（页面刷新后恢复）
    const savedSessionState = sessionStorage.getItem(SESSION_STATE_KEY);
    if (savedSessionState) {
      try {
        const { lastActivity, savedAt } = JSON.parse(savedSessionState);
        const currentTime = Date.now();
        const timeSinceLastActivity = currentTime - lastActivity;
        const timeSinceSaved = currentTime - savedAt;
        
        // 如果保存时间不超过5分钟且会话未过期，恢复会话状态
        if (timeSinceSaved <= 5 * 60 * 1000 && timeSinceLastActivity < SESSION_TIMEOUT) {
          lastActivityRef.current = lastActivity;
          const remainingTime = SESSION_TIMEOUT - timeSinceLastActivity;
          timeoutRef.current = setTimeout(() => {
            performLogout();
          }, remainingTime);
          // 清除保存的状态
          sessionStorage.removeItem(SESSION_STATE_KEY);
        } else {
          // 会话已过期或保存时间过长，执行登出
          sessionStorage.removeItem(SESSION_STATE_KEY);
          performLogout();
          return;
        }
      } catch (error) {
        // 解析失败，清除状态并设置新的超时
        sessionStorage.removeItem(SESSION_STATE_KEY);
        resetSessionTimeout();
      }
    } else {
      // 没有保存的状态，设置初始超时计时器
      resetSessionTimeout();
    }

    // 添加用户活动监听器
    ACTIVITY_EVENTS.forEach(event => {
      document.addEventListener(event, handleUserActivity, true);
    });

    // 添加页面可见性变化监听器
    document.addEventListener('visibilitychange', handleVisibilityChange);

    // 添加页面卸载监听器
    window.addEventListener('beforeunload', handleBeforeUnload);

    // 清理函数
    return () => {
      // 清除超时计时器
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }

      // 移除事件监听器
      ACTIVITY_EVENTS.forEach(event => {
        document.removeEventListener(event, handleUserActivity, true);
      });
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [isAuthenticated, resetSessionTimeout, handleUserActivity, handleVisibilityChange, handleBeforeUnload, performLogout]);

  // 手动重置会话（用于某些特殊操作后）
  const resetSession = useCallback(() => {
    resetSessionTimeout();
  }, [resetSessionTimeout]);

  // 获取剩余会话时间
  const getRemainingTime = useCallback(() => {
    const timeSinceLastActivity = Date.now() - lastActivityRef.current;
    return Math.max(0, SESSION_TIMEOUT - timeSinceLastActivity);
  }, []);

  return {
    resetSession,
    getRemainingTime,
    performLogout
  };
};

export default useSessionManager;